package com.huilan.base.esl.service.impl;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.huilan.base.esl.api.ChatApi;
import com.huilan.base.esl.api.EventApi;
import com.huilan.base.esl.pojo.ApiResult;
import com.huilan.base.esl.pojo.ApiResultBuild;
import com.huilan.base.esl.pojo.po.chat.ChatPo;
import com.huilan.base.esl.pojo.po.event.EventPo;
import com.huilan.base.esl.service.fs.EslClient;
import lombok.extern.slf4j.Slf4j;
import org.freeswitch.esl.client.transport.CommandResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class EventImpl extends BaseImpl implements EventApi {


    @Override
    public ApiResult send(EventPo eventPo) {
        return sendevent(eventPo);
    }

    /**
     * @Description
     * String command = "sendevent SEND_MESSAGE\n"+
     *                 "profile: internal\n"+
     *                 "content-length: 2\n"+
     *                 "content-type: text/plain\n"+
     *                 "user: 1018\n"+
     *                 "host: 127.0.0.1\n"+
     *                 "\n"+
     *                 "99"
     *                 ;
     * @Return java.lang.String
     * @Author liuwc
     * @Date 2021/3/20 10:57
    */
    private ApiResult sendevent(EventPo eventPo){
        String header = eventPo.getHeader()
                .entrySet()
                .stream()
                .map(s -> s.getKey() + ":" + s.getValue() + "\n")
                .collect(Collectors.joining());
        String command = StrBuilder.create()
                .append("sendevent ").append(eventPo.getEventName()).append("\n")
                .append(header)
                .append("\n")
                .append(eventPo.getBody())
                .toString();
        CommandResponse commandResponse = eslClient.getClient().sendCommand(command);
        return ApiResultBuild.success(commandResponse.getResponse().getBodyLines());
    }

    @Override
    public ApiResult send_message(String user, String content) {
        Map<String, Object> header = new HashMap<>();
        header.put("profile","internal");
        header.put("content-length",content.length());
        header.put("content-type","text/plain");
        header.put("user",user);
        header.put("host",getHost());
        return sendevent(EventPo.builder()
                .eventName("SEND_MESSAGE")
                .header(header)
                .body(content)
                .build());
    }
}
